import 'package:flustars/flustars.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/push/jpush_utils.dart';
import 'package:tracker/pages/home/home/model/user_info_resp.dart';
import 'package:tracker/utils/toast_utils.dart';

typedef UserInfoCallback = void Function(UserInfoData userInfoData);

class UserInfoNotifier extends StateNotifier<UserInfoData> {
  UserInfoNotifier()
      : super(SpUtil.getObject('userInfo') == null
            ? UserInfoData()
            : UserInfoData().fromJson(SpUtil.getObject('userInfo')!));

  void setUserInfo(UserInfoData userInfo) {
    state = userInfo;
    SpUtil.putObject('userInfo', userInfo);
    XLogger.info('用户信息：${userInfo.toJson()}');
    // 用户类型
    // var userType = UserTypeEnum.fromValue(state.type!);
    // 如果电话号码不为空，则注册电话号码
    // if (userInfo.phone != null && userType != UserTypeEnum.agent) {
    //   XLogger.info('注册极光推送：${userInfo.phone}');
    //   // JPushUtils.setAlias(userInfo.phone!);
    // } else {
    //   XLogger.info('移除极光推送');
    //   // JPushUtils.deleteAlias();
    // }
  }

  void removeUserInfo() {
    state = UserInfoData();
    SpUtil.remove('userInfo');
  }

  /// 刷新用户信息
  Future<void> fetchUserInfo(UserInfoCallback? onSuccess) async {
    var res = await get<UserInfoResp, UserInfoResp>('/app/user/info', decodeType: UserInfoResp());
    res.when(
        success: (UserInfoResp resp) {
          if (resp.code == 200) {
            SpUtil.putObject('userInfo', resp.data!);
            setUserInfo(resp.data!);
            onSuccess?.call(resp.data!);
          } else {
            // SpUtil.remove('userInfo');
            // ref.read(userInfoProvider.notifier).state = UserInfoData();
            XLogger.debug(resp.msg ?? '获取用户信息失败');
            ToastUtils.showToast(resp.msg ?? '获取用户信息失败');
          }
        },
        failure: (String msg, int code) {});
  }
}
